<?php
declare (strict_types = 1);

namespace app\controller;

use think\Request;
use app\BaseController;
use think\facade\View;
use app\model\VisitorShowroom as ShowroomModel;
use app\model\ServiceCustomer as CustomerModel;
use app\model\SalesOrder as OrderModel;
use app\model\SettingCar as CarModel;
use app\model\SettingUser as UserModel;
use app\middleware\CheckLogin;

class Sales extends BaseController
{
    // 注册控制器中间件
    protected $middleware = [CheckLogin::class];

    /**
     * 资源显示页面
     *
     * @return \think\Response
     */
    public function index()
    {
        return redirect((string)url('Sales/analysis'));
    }

    /**
     * 数据分析页面
     *
     * @return \think\Response
     */
    public function analysis()
    {
        //拉取人员名单
        $sales = UserModel::where('visible',1)->column('name');
        View::assign('sales',$sales);
        //
        return view('analysis');
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function analysisJson(Request $request)
    {
        //获取时间范围
        $daterange = $request->param('daterange');

        //获取始末日期
        $date = DateInterval($daterange);

        // 查询人员
        $sales = $request->param('sales');
        if(!empty($sales)){
            $where['sales'] = $sales;
        }else{
            $where = array();
        }

        //获取本期接待数据
        $visitorCount = ShowroomModel::whereTime('create_date','between',[$date['thisStart'],$date['thisEnd']])->where($where)->count();
        $data['visitorCount'] = $visitorCount;

        //接待环比
        $lastVisitorCount = ShowroomModel::whereTime('create_date','between',[$date['lastStart'],$date['lastEnd']])->where($where)->count();
        if($lastVisitorCount != 0){
            $data['visitorChainRatio'] = intval(($visitorCount - $lastVisitorCount) / $lastVisitorCount * 100).'%';
        }else{
            $data['visitorChainRatio'] = '无';
        }

        //获取本期邀约数据
        $inviteCount = ShowroomModel::whereTime('create_date','between',[$date['thisStart'],$date['thisEnd']])->where($where)->where('invite',1)->count();
        $data['inviteCount'] = $inviteCount;

        //接待环比
        $lastInviteCount = ShowroomModel::whereTime('create_date','between',[$date['lastStart'],$date['lastEnd']])->where($where)->where('invite',1)->count();
        if($lastInviteCount != 0){
            $data['inviteChainRatio'] = intval(($inviteCount - $lastInviteCount) / $lastInviteCount * 100).'%';
        }else{
            $data['inviteChainRatio'] = '无';
        }

        //获取本期订单数据
        $OrderCount = OrderModel::whereTime('create_date','between',[$date['thisStart'],$date['thisEnd']])->where($where)->count();
        $data['OrderCount'] = $OrderCount;

        //订单环比
        $lastOrderCount = OrderModel::whereTime('create_date','between',[$date['lastStart'],$date['lastEnd']])->where($where)->count();
        if($lastOrderCount != 0){
            $data['orderChainRatio'] = intval(($OrderCount - $lastOrderCount) / $lastOrderCount * 100).'%';
        }else{
            $data['orderChainRatio'] = '无';
        }

        //获取本期交车数据
        $deliverCount = OrderModel::whereTime('deliver_date','between',[$date['thisStart'],$date['thisEnd']])->where($where)->count();
        $data['deliverCount'] = $deliverCount;

        //交车环比
        $lastDeliverCount = OrderModel::whereTime('deliver_date','between',[$date['lastStart'],$date['lastEnd']])->where($where)->count();
        if($lastDeliverCount != 0){
            $data['deliverChainRatio'] = intval(($deliverCount - $lastDeliverCount) / $lastDeliverCount * 100).'%';
        }else{
            $data['deliverChainRatio'] = '无';
        }

        //线图部分
        /////////////////////////////////////////////////////////////////

        //销售顾问接待数据图
    
        //客流数据部分
        $thisStart = $date['thisStart'];
        $lastStart = $date['lastStart'];

        for($x=0;$x<$date['maxDays'];$x++){

            //日期赋值
            $lineData[$x]['datetag'] = date('d',$thisStart)."日";

            //客流数据图

            //本期数据
            $thisVisitorData = ShowroomModel::where('create_date',date('Y-m-d H:i:s',$thisStart))->where($where)->count();
            $lineData[$x]['thisVisitorData'] = $thisVisitorData;

            //上期数据
            $lastVisitorData = ShowroomModel::where('create_date',date('Y-m-d H:i:s',$lastStart))->where($where)->count();
            $lineData[$x]['lastVisitorData'] = $lastVisitorData;

            //订单数据图

            //本期数据
            $thisOrderData = OrderModel::where('create_date',date('Y-m-d H:i:s',$thisStart))->where($where)->count();
            $lineData[$x]['thisOrderData'] = $thisOrderData;

            //上期数据
            $lastOrderData = OrderModel::where('create_date',date('Y-m-d H:i:s',$lastStart))->where($where)->count();
            $lineData[$x]['lastOrderData'] = $lastOrderData;

            //交车数据图

            //本期数据
            $thisDeliverData = OrderModel::where('deliver_date',date('Y-m-d H:i:s',$thisStart))->where($where)->count();
            $lineData[$x]['thisDeliverData'] = $thisDeliverData;

            //上期数据
            $lastDeliverData = OrderModel::where('deliver_date',date('Y-m-d H:i:s',$lastStart))->where($where)->count();
            $lineData[$x]['lastDeliverData'] = $lastDeliverData;


            //本周期日期增加
            $thisStart = strtotime("+1day",$thisStart);//加一天
            $thisData = array();

            //上周期日期增加
            $lastStart = strtotime("+1day",$lastStart);//加一天
            $lastData = array();
            
        }

        $data['lineData'] = $lineData;
        //线图结束
        ////////////////////////////////////////////////

        //统计区间数据
        $statisticsData = $this->statistics($sales,$date);

        //在店接待时长占比
        if(!empty($statisticsData['length'])){
            $length = $statisticsData['length'];
            $lengthRatio['label'] = array();
            $lengthRatio['data'] = array(); 
            foreach ($length as $key => $value) {
                if($key == 180){
                    array_push($lengthRatio['label'],'120分钟以上');
                }else{
                    array_push($lengthRatio['label'],$key.'分钟');
                }
                array_push($lengthRatio['data'],$value);
            }
        }else{
            $lengthRatio['label'] = array("无数据");
            $lengthRatio['data'] = array(0);
        }
        $data['lengthRatio'] = $lengthRatio;

        //关注车型数据
        if(!empty($statisticsData['vehicle'])){
            $vehicle = $statisticsData['vehicle'];
            $vehicleRatio['label'] = array();
            $vehicleRatio['data'] = array(); 
            foreach ($vehicle as $key => $value) {
                array_push($vehicleRatio['label'],$key);
                array_push($vehicleRatio['data'],$value);
            }
        }else{
            $vehicleRatio['label'] = array("无数据");
            $vehicleRatio['data'] = array(0);
        }
        $data['vehicleRatio'] = $vehicleRatio;

        //联系方式留存数据
        if(!empty($statisticsData['contact'])){
            $contact = $statisticsData['contact'];
            $contactRatio['label'] = array();
            $contactRatio['data'] = array(); 
            foreach ($contact as $key => $value) {
                array_push($contactRatio['label'],$key);
                array_push($contactRatio['data'],$value);
            }
        }else{
            $contactRatio['label'] = array("无数据");
            $contactRatio['data'] = array(0);
        }
        $data['contactRatio'] = $contactRatio;

        //首再次来店占比数据
        if(!empty($statisticsData['type'])){
            $type = $statisticsData['type'];
            $typeRatio['label'] = array();
            $typeRatio['data'] = array(); 
            foreach ($type as $key => $value) {
                array_push($typeRatio['label'],$key);
                array_push($typeRatio['data'],$value);
            }     
        }else{
            $typeRatio['label'] = array("无数据");
            $typeRatio['data'] = array(0);
        }
        $data['typeRatio'] = $typeRatio;

        //性别数据
        if(!empty($statisticsData['sex'])){
            $sex = $statisticsData['sex'];
            $sexRatio['label'] = array();
            $sexRatio['data'] = array(); 
            foreach ($sex as $key => $value) {
                //将男1女0的数据翻译成标签
                if($key == 1){
                    array_push($sexRatio['label'],'男');
                }else{
                    array_push($sexRatio['label'],'女');
                }
                array_push($sexRatio['data'],$value);
            }
            
        }else{
            $sexRatio['label'] = array("无数据");
            $sexRatio['data'] = array(0);
        }
        $data['sexRatio'] = $sexRatio;

        //首次成交比例
        if(!empty($statisticsData['firstToOrder'])){
            $firstToOrder = $statisticsData['firstToOrder'];
            $firstToOrderRatio['label'] = array();
            $firstToOrderRatio['data'] = array(); 
            foreach ($firstToOrder as $key => $value) {
                array_push($firstToOrderRatio['label'],$key);
                array_push($firstToOrderRatio['data'],$value);
            }
            $data['firstToOrderRatio'] = $firstToOrderRatio;
        }

        //再次成交比例
        if(!empty($statisticsData['lastToOrder'])){
            $lastToOrder = $statisticsData['lastToOrder'];
            $lastToOrderRatio['label'] = array();
            $lastToOrderRatio['data'] = array(); 
            foreach ($lastToOrder as $key => $value) {
                array_push($lastToOrderRatio['label'],$key);
                array_push($lastToOrderRatio['data'],$value);
            }
            $data['lastToOrderRatio'] = $lastToOrderRatio;
        }
        //承保率
        if(!empty($statisticsData['insurance'])){
            $insurance['label'] = array('承保','未承保');
            $insurance['data'] = $statisticsData['insurance']; 
            $data['insurance'] = $insurance;
        }

        //本周期日期
        $data['thisStart'] = date('m月d日',$date['thisStart']);
        $data['thisEnd'] = date('m月d日',$date['thisEnd']);
        
        return json($data);

    }

    private function statistics($sales,$date)
    {

        // 查询人员
        if(!empty($sales)){
            $where['sales'] = $sales;
        }else{
            $where = array();
        }

        $startDate = $date['thisStart'];
        $endDate = $date['thisEnd'];

        //停留时长
        $length = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->Distinct(true)->column('length');

        for ($i=0; $i < count($length); $i++) { 
            $statisticsData['length'][$length[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where('length',$length[$i])->count();
        }

        //车型比例
        $vehicle = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->Distinct(true)->column('vehicle');

        for ($i=0; $i < count($vehicle); $i++) { 
            $statisticsData['vehicle'][$vehicle[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where('vehicle',$vehicle[$i])->count();
        }

        //首再次来店
        $statisticsData['type']['首次'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where('type','首次')->count();
        $statisticsData['type']['再次'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where('type','再次')->count();


        //留取联系方式比例
        $contact = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->Distinct(true)->column('contact');

        for ($i=0; $i < count($contact); $i++) { 
            $statisticsData['contact'][$contact[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where('contact',$contact[$i])->count();
        }

        //性别数据,男1女2
        $sex = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->Distinct(true)->column('sex');

        for ($i=0; $i < count($sex); $i++) { 
            $statisticsData['sex'][$sex[$i]] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where('sex',$sex[$i])->count();
        }

        //首次接待成交率
        $statisticsData['firstToOrder']['订单'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where(['type' => '首次','order' => 1])->count();
        $statisticsData['firstToOrder']['未订'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where(['type' => '首次','order' => 0])->count();

        //再次接待成交率
        $statisticsData['lastToOrder']['订单'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where(['type' => '再次','order' => 1])->count();
        $statisticsData['lastToOrder']['未订'] = ShowroomModel::whereTime('create_date','between',[$startDate,$endDate])->where($where)->where(['type' => '再次','order' => 0])->count();

        //承保率
        $totalCustomerCount = CustomerModel::whereTime('deliver_date','between',[$date['thisStart'],$date['thisEnd']])->where($where)->count();
        $insuranceCustomerCount = CustomerModel::whereTime('deliver_date','between',[$date['thisStart'],$date['thisEnd']])->where($where)->where('insurance_company','NOTNULL')->count();
        $notInsuranceCustomerCount = $totalCustomerCount - $insuranceCustomerCount;
        $statisticsData['insurance'][0] = $insuranceCustomerCount;
        $statisticsData['insurance'][1] = $notInsuranceCustomerCount;
        ////////////////////////

        return $statisticsData;
    }
}
